package com.wanhe.base.net;


import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.google.gson.GsonBuilder;
import com.orhanobut.logger.Logger;
import com.wanhe.base.BaseApplication;
import com.wanhe.base.util.SPUtils;
import com.wanhe.base.util.ViewUtil;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Singleton;

import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import okio.Buffer;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

import static com.wanhe.base.BaseApplication.context;

/**
 * Created by Administrator on 2017/3/14.
 */
@Singleton
public class RequestTool {


    private String BASE_URL;
    protected Retrofit retrofit;
    private OkHttpClient httpClient;

    public String getBASE_URL() {
        return BASE_URL;
    }

    public void setBASE_URL(String BASE_URL) {
        this.BASE_URL = BASE_URL;
    }

    public ServerApiImp getServerApi() {
        return serverApi;
    }

    private ServerApiImp serverApi;

    public RequestTool(String BASE_URL ) {
        this.BASE_URL = BASE_URL;
        initTool();
    }

    public void initTool(){
        configureOkHttp();
        configureRetrofit();
        configureService();
    }

    private void configureRetrofit() {
//        BASE_URL = "http://"+ SPUtils.getIp()+":"+SPUtils.getPort();
        Logger.d("RequestTool","configureRetrofit="+BASE_URL);

        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().create()))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(httpClient)
                .build();
    }

    public void resetRetrofit(String url){
        Logger.d("RequestTool","resetRetrofit="+url);
        retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().create()))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(httpClient)
                .build();
    }
    private OkHttpClient configureOkHttp() {

        Cache cache = new Cache(new File(context.getCacheDir(), "HttpCache"),
                1024 * 1024 * 100);

        OkHttpClient.Builder builder  = new OkHttpClient.Builder().cache(cache)
                .retryOnConnectionFailure(true)
                .addInterceptor(sLoggingInterceptor)
//                .addInterceptor(sRewriteCacheControlInterceptor)
//                .addNetworkInterceptor(sRewriteCacheControlInterceptor)
                .connectTimeout(10, TimeUnit.SECONDS);


        return httpClient = builder.build();

//addInterceptor(logging).
    }


    private OkHttpClient configureOkHttp(Interceptor interceptor) {
        if (interceptor == null) {
            throw new NullPointerException("Interceptor can't null");
        }
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        return httpClient = new OkHttpClient.Builder().addInterceptor(interceptor).addInterceptor(logging).build();
    }

    private OkHttpClient configureOkHttp(List<Interceptor> interceptorList) {
        if (interceptorList == null || interceptorList.size() == 0) return null;
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        for (Interceptor interceptor : interceptorList) {
            builder.addInterceptor(interceptor);
        }
        return httpClient = builder.build();
    }

    private void configureService() {
        serverApi = retrofit.create(ServerApiImp.class);
    }

    /**
     * 打印返回的json数据拦截器
     */
    private static final Interceptor sLoggingInterceptor = new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            final Request request = chain.request();
            long t1 = System.nanoTime();//请求发起的时间
            Buffer requestBuffer = new Buffer();
            if (request.body() != null) {
                request.body().writeTo(requestBuffer);
            } else {
                Logger.d("CallRing", "request.body() == null");
            }
            //打印url信息
            Logger.w(request.url() + (request.body() != null ? "?" + _parseParams(request.body(), requestBuffer) : ""));
            long t2 = System.nanoTime();//收到响应的时间
            final Response response = chain.proceed(request);
            ResponseBody responseBody = response.peekBody(1024 * 1024);
            Logger.w(String.format("接收响应: [%s] %n时间:%.1fms%n%s返回data:%s",
                    response.request().url(),
                    (t2 - t1) / 1e6d,
                    response.headers(),
                    responseBody.string()));
            return response;
        }
    };

    @NonNull
    private static String _parseParams(RequestBody body, Buffer requestBuffer) throws UnsupportedEncodingException {
        if (body.contentType() != null && !body.contentType().toString().contains("multipart")) {
            return URLDecoder.decode(requestBuffer.readUtf8(), "UTF-8");
        }
        return "null";
    }

//    /**
//     * 云端响应头拦截器，用来配置缓存策略
//     * Dangerous interceptor that rewrites the server's cache-control header.
//     */
//    private static final Interceptor sRewriteCacheControlInterceptor = new Interceptor() {
//
//        @Override
//        public Response intercept(Chain chain) throws IOException {
//            Request request = chain.request();
//            if (!NetUtil.isNetworkAvailable(mContext)) {
//                request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
//                Logger.e("no network");
//            }
//            Response originalResponse = chain.proceed(request);
//
//            if (NetUtil.isNetworkAvailable(mContext)) {
//                //有网的时候读接口上的@Headers里的配置，你可以在这里进行统一的设置
//                String cacheControl = request.cacheControl().toString();
//                return originalResponse.newBuilder()
//                        .header("Cache-Control", cacheControl)
//                        .removeHeader("Pragma")
//                        .build();
//            } else {
//                return originalResponse.newBuilder()
//                        .header("Cache-Control", "public, " + CACHE_CONTROL_CACHE)
//                        .removeHeader("Pragma")
//                        .build();
//            }
//        }
//    };


}
